﻿define([], function () {
    return function ($scope, $http, $filter, Services) {
        var uri = "http://efm.develop.local/";
        var serviceUri = uri + "api/";

        $scope.hasError = false;

        $scope.isIE9 = function () {
            return $('html').hasClass('k-ie9');
        };

        $scope.isIE10or11 = function () {
            return $('html').hasClass('k-ie10') || $('html').hasClass('k-ie11');
        };

        $scope.initPopupDate = function (name, date, id) {
            Services.initPopupDate({ name: name, date: date, id: id });
        };

        $scope.initPopup = function (index, type, id, ports, selected) {
            Services.initPopup({ index: index, type: type, id: id, ports: ports, selected: selected });
        };

        $scope.initPopupLay = function (data, id) {
            Services.initPopupLay({ LayCan: data, id: id });
        };

        $scope.changedId = function (item) {
            dataItem.changed = true;
        };

        $scope.assignToAll = function (value) {
            var objs = document.getElementsByName('Input' + Services.date.name + Services.date.id);
            for (var i = 0; i < objs.length; i++)
                objs[i].value = value;
        };

        $scope.createCell = function (style, value) {
            var xml;
            xml = '  <Cell ss:StyleID="' + style + '">\n';
            xml += '    <Data ss:Type="String">';
            xml += value + '</Data>\n';
            xml += '  </Cell>\n';
            return xml;
        };

        $scope.createCellUrl = function (link, value) {
            var xml;
            xml = '  <Cell ss:StyleID="Hyperlink" ss:HRef="' + link + '">\n';
            xml += '    <Data ss:Type="String">';
            xml += value + '</Data>\n';
            xml += '  </Cell>\n';
            return xml;
        };

        $scope.download = function (xml) {
            var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            var fileName = 'Fixtures.xls';
            var blob = new Blob([xml], {
                'type': contentType
            });
            if ($scope.isIE9()) {
                $.ajax({
                    url: "Contest/SetXml",
                    type: "POST",
                    dataType: "json",
                    async: false,
                    contentType: 'application/json; charset=utf-8',
                    data: "{ 'xmlString':'" + xml + "' }"
                });
                window.location.href = uri + 'Contest/DownloadExcel';
                //var w = window.open("about:blank", "_blank");
                //w.document.write(xml);
                //w.close();
                //w.document.execCommand('SaveAs', true, fileName);
            }
            else if ($scope.isIE10or11())
                window.navigator.msSaveBlob(blob, fileName);
            else {
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.style = "visibility:hidden";
                link.download = fileName;
                link.click();
            }
        };

        $scope.exportExcel = function () {
            var jsonObject = $('#grid').data('kendoGrid').dataSource.data();
            var columns = ['Fixture Name', 'Lay/Can', 'Owner', 'Charterer', 'Loading Port', 'Discharge Port', 'Voyage Order Date', 'Loading Order Date', 'Discharge Order Date',
                           'Bill Of Laden Date', 'Letter Of Indemnity Date', 'Freight Invoice Date', 'Commission Invoice Date', 'Has Demurrage'];

            var XmlHeader = '<?xml version="1.0" encoding="utf-8"?>\n' + '<?mso-application progid="Excel.Sheet"?>\n' + '<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet">\n' +
                            '<Styles>\n'+'<Style ss:ID="Normal">\n'+'<Alignment ss:Vertical="Center" />\n'+'</Style>\n'+
                            '<Style ss:ID="MultiLine">\n'+'<Alignment ss:Vertical="Center" ss:WrapText="1"/>\n'+'</Style>\n'+
                            '<Style ss:ID="Hyperlink" ss:Parent="Normal">\n' + '<Font  ss:Color="#0000FF" ss:Underline="Single"/>\n' +
                            '</Style>\n' + '</Styles>\n' + '<Worksheet ss:Name="FixturesSheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' + '<Table>\n';
            var XmlFooter = '</Table>\n' + '</Worksheet>\n' + '</Workbook>\n';
            var xml;
            var size = '<Column ss:AutoFitWidth="0" ss:Width="130.00"/>\n';
            var data = typeof jsonObject != "object"
                     ? JSON.parse(jsonObject)
                     : jsonObject;
            xml = XmlHeader;
            //columns size
            for (var i = 0; i < columns.length; i++)
                xml += size;
            //columns name
            xml += '<Row>\n';
            for (var i = 0; i < columns.length; i++) 
                xml += $scope.createCell('MultiLine', columns[i]);
            xml += '</Row>\n';
            //columns data
            for (var i = 0; i < data.length; i++)
                xml += $scope.fillRow(data[i]);

            xml += XmlFooter;

            $scope.download(xml);
        };

        $scope.checkField = function (field) {
            if (field == undefined)
                return '';
            field = field.replace('<', '');
            field = field.replace('>', '');
            return field;
        };

        $scope.fillPorts = function (ports, index) {
            if (ports.length > index) {
                var msg;
                if (ports[index].Chat.length > 0)
                    msg = ports[index].Chat[ports[index].Chat.length - 1].Message;
                return $scope.createCell('MultiLine', $scope.checkField(ports[index].Name) + '&#10;' +
                                                      $scope.checkField(ports[index].ETAMarker) + ' ' + $scope.getDateTimeString(ports[index].ETA_NORTime) + '&#10;' +
                                                      $scope.checkField(ports[index].ETDMarker) + ' ' + $scope.getDateTimeString(ports[index].ETD_ATDTime) + '&#10;' +
                                                      $scope.checkField(msg));
            }
            return $scope.createCell('MultiLine', '');
        };

        $scope.fillRow = function (row) {
            var xml;
            xml = '<Row>\n';
            xml += $scope.createCellUrl($scope.checkField(row.LinkToDemurrage), $scope.checkField(row.Vessel.Name) + ' C/P ' + $scope.getDateString(row.CPDate));
            xml += $scope.createCell('MultiLine', 'From: ' + $scope.getDateTimeString(row.LayCan.FromDate) + '&#10;To: ' + $scope.getDateTimeString(row.LayCan.ToDate) + '&#10;');
            xml += $scope.createCell('MultiLine', $scope.checkField(row.Owner.Name) + '&#10;');
            xml += $scope.createCell('MultiLine', $scope.checkField(row.Charterer.Name) + '&#10;');
            xml += $scope.fillPorts(row.LoadingPorts, row.SelectedLoadingPort);
            xml += $scope.fillPorts(row.DischargePorts, row.SelectedDischargePort);
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.VoyageOrderDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.LoadingOrderDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.DischargeOrderDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.BillOfLadenDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.LetterOfIndemnityDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.FreightInvoiceDate));
            xml += $scope.createCell('Normal', $scope.getDateTimeString(row.CommissionInvoiceDate));
            xml += $scope.createCellUrl($scope.checkField(row.LinkToDemurrage), $scope.checkField(row.DemurrageStatus.value));
            xml += '</Row>\n';
            return xml;
        };

        $scope.saveFixture = function () {
            var ListFixtures = $("#grid").data().kendoGrid.dataSource.view();
            var sendList = [];

            for (var i = 0; i < ListFixtures.length; i++) 
                if (ListFixtures[i].changed) {
                    sendList.push(jQuery.extend(true, {}, ListFixtures[i]));
                    ListFixtures[i].changed = false;
                }
            if (sendList.length > 0) {
                $scope.loader(true);
                $http({
                    url: serviceUri + 'fixture',
                    method: 'POST',
                    data: JSON.stringify($scope.statusToInt(sendList))
                }).success(function (data) {
                    $scope.loader(false);
                    $scope.showErrorDiv(false);
                }).error(function (data) {
                    $scope.loader(false);
                    $scope.showErrorDiv(true);
                });
            }
        };
        
        $scope.sendList = [];

        $scope.open = function (closeFiWindow) {
            if ($scope.sendList.length > 0)
                closeFiWindow.open().center();
        };

        $scope.defineClosedItems = function () {
            var ListFixtures = $("#grid").data().kendoGrid.dataSource.view();
            $scope.sendList = [];

            for (var i = 0; i < ListFixtures.length; i++)
                if (document.getElementById(ListFixtures[i].Id).checked)
                    $scope.sendList.push(ListFixtures[i]);
        };

        $scope.closeFixture = function () {
            for (var i = 0; i < $scope.sendList.length; i++)
                $("#grid").data().kendoGrid.dataSource.remove($scope.sendList[i]);

            if ($scope.sendList.length > 0) {
                $scope.loader(true);
                $http({
                    url: serviceUri + 'fixtureextend',
                    method: 'POST',
                    data: JSON.stringify($scope.statusToInt($scope.sendList)),
                }).success(function (data) {
                    $scope.loader(false);
                    $scope.showErrorDiv(false);
                }).error(function (data) {
                    $scope.loader(false);
                    $scope.showErrorDiv(true);
                });
            }
        };

        $scope.searchFixture = function (condition, dateTo, dateFrom, demurrageStatus, isActiveFixtures,
                                         isCurrentUserPrimary, isCurrentUserSecondary) {
            $scope.loader(true);

            //random
            if (condition == '2147483647') {
                $http({
                    url: serviceUri + "fixture/2/2",
                    method: "GET",
                }).success(function (data) {
                    $("#grid").data('kendoGrid').dataSource.data($scope.statusToString(data));
                    $scope.showErrorDiv(false);
                    $scope.loader(false);
                }).error(function (data) {
                    $scope.loader(false);
                    $scope.showErrorDiv(true);
                });
                return;
            }
            //random
            $http({
                url: serviceUri + 'fixtureextend',
                method: "GET",
                params: {
                    Condition: condition, DateTo: $scope.getDateString(dateTo), DateFrom: $scope.getDateString(dateFrom),
                    DemurrageStatus: demurrageStatus,IsActiveFixtures: isActiveFixtures, IsCurrentUserPrimary: isCurrentUserPrimary,
                    IsCurrentUserSecondary: isCurrentUserSecondary, fixtureType: "Voyage"
                }
            }).success(function (data) {
                var grid = $("#grid").data('kendoGrid');
                grid.dataSource.data($scope.statusToString(data));
                grid.dataSource.query({
                    page: 1,
                    group: grid.dataSource.group(),
                    filter: grid.dataSource.filter(),
                    sort: grid.dataSource.sort(),
                    pageSize: grid.dataSource.pageSize()
                });
                //grid.dataSource.page(1);
                $scope.loader(false);
                $scope.showErrorDiv(false);
            }).error(function (data) {
                $scope.loader(false);
                $scope.showErrorDiv(true);
            });
        };

        $scope.getDateString = function (date) {
            if (date == '' || date == undefined)
                return '';
            return $filter('date')(date, 'dd.MM.yyyy');
        };

        $scope.getDateTimeString = function (date) {
            if (date == '' || date == undefined)
                return '';
            return $filter('date')(date, 'dd.MM.yyyy H:mm:ss');
        };

        $scope.loader = function (bool) {
            kendo.ui.progress($("#loading"), bool);
        };

        $scope.showErrorDiv = function (value) {
            var div = document.getElementById('errorDiv');
            if (value)
                div.className = '';
            else
                div.className = 'hiddiv';

        };

        $scope.statusToString = function (array) {
            for (var i = 0; i < array.length; i++) {
                switch (array[i].DemurrageStatus) {
                    case 0:
                        array[i].DemurrageStatus = { value: 'Unknown', style: 'turStatus' };
                        break;
                    default:
                        array[i].DemurrageStatus = { value: 'Not Exist', style: 'turStatus' };
                        break;
                    case 2:
                        array[i].DemurrageStatus = { value: 'Reminder Sent', style: 'turStatus' };
                        break;
                    case 3:
                        array[i].DemurrageStatus = { value: 'Claim Received', style: 'yellowStatus' };
                        break;
                    case 4:
                        array[i].DemurrageStatus = { value: 'Claim Forwarded', style: 'yellowStatus' };
                        break;
                    case 5:
                        array[i].DemurrageStatus = { value: 'Claim Acknowledged', style: 'blueStatus' };
                        break;
                    case 6:
                        array[i].DemurrageStatus = { value: 'Accepted', style: 'blueStatus' };
                        break;
                    case 7:
                        array[i].DemurrageStatus = { value: 'No', style: 'greenStatus' };
                        break;
                    case 8:
                        array[i].DemurrageStatus = { value: 'Invoiced', style: 'greenStatus' };
                        break;
                }
                array[i].changed = false;
                array[i].Id = array[i].Id.replace(/ /g, "_");
                array[i].Type = $scope.setTypeOf(array[i].Type);
                array[i].SelectedLoad = 0;
                array[i].SelectedDisch = 0;
                if (!$scope.isExplorer() || $scope.isIE9()) {
                    array[i].CPDate = $scope.returnDateOfZone(array[i].CPDate);
                    array[i].CommissionInvoiceDate = $scope.returnDateOfZone(array[i].CommissionInvoiceDate);
                    array[i].VoyageOrderDate = $scope.returnDateOfZone(array[i].VoyageOrderDate);
                    array[i].LoadingOrderDate = $scope.returnDateOfZone(array[i].LoadingOrderDate);
                    array[i].DischargeOrderDate = $scope.returnDateOfZone(array[i].DischargeOrderDate);
                    array[i].BillOfLadenDate = $scope.returnDateOfZone(array[i].BillOfLadenDate);
                    array[i].LetterOfIndemnityDate = $scope.returnDateOfZone(array[i].LetterOfIndemnityDate);
                    array[i].FreightInvoiceDate = $scope.returnDateOfZone(array[i].FreightInvoiceDate);
                    array[i].LoadingPorts = $scope.setPortDatesOf(array[i].LoadingPorts);
                    array[i].DischargePorts = $scope.setPortDatesOf(array[i].DischargePorts);
                }
                else {
                    array[i].CPDate = $scope.checkDate(array[i].CPDate);
                    array[i].CommissionInvoiceDate = $scope.checkDate(array[i].CommissionInvoiceDate);
                    array[i].VoyageOrderDate = $scope.checkDate(array[i].VoyageOrderDate);
                    array[i].LoadingOrderDate = $scope.checkDate(array[i].LoadingOrderDate);
                    array[i].DischargeOrderDate = $scope.checkDate(array[i].DischargeOrderDate);
                    array[i].BillOfLadenDate = $scope.checkDate(array[i].BillOfLadenDate);
                    array[i].LetterOfIndemnityDate = $scope.checkDate(array[i].LetterOfIndemnityDate);
                    array[i].FreightInvoiceDate = $scope.checkDate(array[i].FreightInvoiceDate);
                    array[i].LoadingPorts = $scope.setPortDatesOfEX(array[i].LoadingPorts);
                    array[i].DischargePorts = $scope.setPortDatesOfEX(array[i].DischargePorts);
                }
            }
            return array;
        };

        $scope.checkDate = function (value) {
            if (value == null || value=="")
                return null
            return new Date(value);
        };

        $scope.isExplorer = function () {
            return window.navigator.userAgent.indexOf('MSIE') > -1 || window.navigator.userAgent.indexOf('rv') > -1;
        };

        $scope.returnDateOfZone = function (value) {
            if (value == null)
                return null;
            var dt = new Date(value);
            dt.setHours(dt.getHours() + dt.getTimezoneOffset() / 60);
            return dt;
        };

        $scope.returnDateOnZone = function (date) {
            if (date == null)
                return null;
            var value = new Date(date);
            value.setHours(value.getHours() - value.getTimezoneOffset() / 60);
            return value;
        };

        $scope.statusToInt = function (arr) {
            var array = JSON.parse(JSON.stringify(arr));
            for (var i = 0; i < array.length; i++) {
                switch (array[i].DemurrageStatus.value) {
                    default:
                        array[i].DemurrageStatus = 0;
                        break;
                    case 'Not Exist':
                        array[i].DemurrageStatus = 1;
                        break;
                    case 'Reminder Sent':
                        array[i].DemurrageStatus = 2;
                        break;
                    case 'Claim Received':
                        array[i].DemurrageStatus = 3;
                        break;
                    case 'Claim Forwarded':
                        array[i].DemurrageStatus = 4;
                        break;
                    case 'Claim Acknowledged':
                        array[i].DemurrageStatus = 5;
                        break;
                    case 'Accepted':
                        array[i].DemurrageStatus = 6;
                        break;
                    case 'No':
                        array[i].DemurrageStatus = 7;
                        break;
                    case 'Invoiced':
                        array[i].DemurrageStatus = 8;
                        break;
                }
                array[i].Id = array[i].Id.replace(/_/g, ' ');
                array[i].SelectedLoad = undefined;
                array[i].SelectedDisch = undefined;
                array[i].changed = undefined;
                array[i].Type = $scope.setTypeOn(array[i].Type);
                array[i].CPDate = $scope.returnDateOnZone(array[i].CPDate);
                array[i].CommissionInvoiceDate = $scope.returnDateOnZone(array[i].CommissionInvoiceDate);
                array[i].VoyageOrderDate = $scope.returnDateOnZone(array[i].VoyageOrderDate);
                array[i].LoadingOrderDate = $scope.returnDateOnZone(array[i].LoadingOrderDate);
                array[i].DischargeOrderDate = $scope.returnDateOnZone(array[i].DischargeOrderDate);
                array[i].BillOfLadenDate = $scope.returnDateOnZone(array[i].BillOfLadenDate);
                array[i].LetterOfIndemnityDate = $scope.returnDateOnZone(array[i].LetterOfIndemnityDate);
                array[i].FreightInvoiceDate = $scope.returnDateOnZone(array[i].FreightInvoiceDate);
                array[i].LoadingPorts = $scope.setPortDatesOn(array[i].LoadingPorts);
                array[i].DischargePorts = $scope.setPortDatesOn(array[i].DischargePorts);
            }
            return array;
        };

        $scope.setTypeOf = function (value) {
            if (value == 'SingleVoyage')
                return 'VOY';
            if (value == 'CoaVoyage')
                return 'COA';
            return value;
        };

        $scope.setTypeOn = function (value) {
            if (value == 'VOY')
                return 'SingleVoyage';
            if (value == 'COA')
                return 'CoaVoyage';
            return value;
        };

        $scope.setPortDatesOf = function (array) {
            if (array.length != 0) {
                array.sort(compare);
                array = $scope.checkPortsName(array);
                for (var i = 0; i < array.length; i++) {
                    array[i].ETA_NORTime = $scope.returnDateOfZone(array[i].ETA_NORTime);
                    array[i].AATime = $scope.returnDateOfZone(array[i].AATime);
                    array[i].ETB_ATBTime = $scope.returnDateOfZone(array[i].ETB_ATBTime);
                    array[i].ETD_ATDTime = $scope.returnDateOfZone(array[i].ETD_ATDTime);
                    array[i].SldDate = $scope.returnDateOfZone(array[i].SldDate);
                }
            }
            return array;
        };

        $scope.setPortDatesOn = function (arr) {
            var array = arr.slice(0);
            array = $scope.checkPortsName(array);
            for (var i = 0; i < array.length; i++) {
                array[i].ETA_NORTime = $scope.returnDateOnZone(array[i].ETA_NORTime);
                array[i].AATime = $scope.returnDateOnZone(array[i].AATime);
                array[i].ETB_ATBTime = $scope.returnDateOnZone(array[i].ETB_ATBTime);
                array[i].ETD_ATDTime = $scope.returnDateOnZone(array[i].ETD_ATDTime);
                array[i].SldDate = $scope.returnDateOnZone(array[i].SldDate);
            }
            return array;
        };

        $scope.setPortDatesOfEX = function (array) {
            if (array.length != 0) {
                array.sort(compare);
                array = $scope.checkPortsName(array);
                for (var i = 0; i < array.length; i++) {
                    array[i].ETA_NORTime = $scope.checkDate(array[i].ETA_NORTime);
                    array[i].AATime = $scope.checkDate(array[i].AATime);
                    array[i].ETB_ATBTime = $scope.checkDate(array[i].ETB_ATBTime);
                    array[i].ETD_ATDTime = $scope.checkDate(array[i].ETD_ATDTime);
                    array[i].SldDate = $scope.checkDate(array[i].SldDate);
                }
            }
            return array;
        };

        function compare(a, b) {
            if (a.Sequence < b.Sequence)
                return -1;
            if (a.Sequence > b.Sequence)
                return 1;
            return 0;
        }

        $scope.getSequence = function (array, i) {
            if (i == 0)
                return 1;
            return array[i - 1].Sequence + 1;
        };

        $scope.checkPortsName = function (array) {
            for (var i = 0; i < array.length; i++) {
                if (array[i].Sequence == null || array[i].Sequence == undefined) {
                    if (i == 0)
                        array[i].Sequence = 1;
                    else
                        array[i].Sequence = array[i - 1].Sequence + 1;
                }
                if (array[i].Name == undefined || array[i].Name == "") {
                    array[i].Name = $scope.uniqueName(array, '(No_Name)', i);
                    array[i].Sequence = $scope.getSequence(array, i);
                }
                else {
                    array[i].Name = $scope.uniqueName(array, array[i].Name, i);
                    array[i].Sequence = $scope.getSequence(array, i);
                }
                if (array[i].FinalCalculationOption == null || array[i].FinalCalculationOption == undefined)
                    array[i].FinalCalculationOption = 0;
            }
            return array;
        };

        $scope.uniqueName = function (array, name, index) {
            for (var i = 0; i < array.length; i++) 
                if (array[i].Name == name && i != index) {
                    name += '*';
                    i = -1;
                }
            return name;
        };

        //sorry ;(
        var lastMouseX, lastMouseY;

        $("#grid").on("mousemove", function (e) {
            lastMouseX = e.pageX;
            lastMouseY = e.pageY;
        });

        $scope.windowCalc = function () {
            $(".k-window").css({ top: lastMouseY, left: lastMouseX, });
        };
        //sorry
    };
    });
